﻿using System;
using System.Json;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using JeffWilcox.Utilities.Silverlight;

namespace MailRuWrapper.Client
{
    public static class Extensions
    {
        public static String MD5Hash(this string source)
        {
            return MD5.GetMd5String(source);
        }

        public static DateTime ToDateTime(this JsonValue source)
        {
            if (source == null)
                return DateTime.MinValue;

            if (source.JsonType == JsonType.String && (string)source != "")
            {
                return ((string) source).ToDateTime();
            }

            if (source.JsonType == JsonType.Number)
            {
                return new DateTime(1970, 1, 1) + new TimeSpan(((Int64)source) * TimeSpan.TicksPerSecond);
            }
            return DateTime.MinValue;
        }

        public static int ToInt(this JsonValue source)
        {
            switch (source.JsonType)
            {
                case JsonType.String:
                    return Int32.Parse((string)source);
                case JsonType.Number:
                    return source;

            }
            throw new NotImplementedException(source.JsonType.ToString());
        }

        public static Boolean ToBoolean(this JsonValue source)
        {
            switch (source.JsonType)
            {
                case JsonType.String:
                    return ((string)source) == "1";
                case JsonType.Number:
                    return source == 1;
                case JsonType.Boolean:
                    return (bool)source;
            }
            throw new NotImplementedException(source.JsonType.ToString());
        }

        public static int ToInt(this string source)
        {
            return Int32.Parse(source);
        }

        public static Uri ToUri(this string source)
        {
            return new Uri(source);
        }

        public static Boolean ToBoolean(this string source)
        {
            return source == "1";
        }

        public static DateTime ToDateTime(this string source)
        {
            if (String.IsNullOrEmpty(source))
            {
                return DateTime.MinValue;
            }
            int _i;
            if (Int32.TryParse((source), out _i))
            {
                return new DateTime(1970, 1, 1) + new TimeSpan(_i * TimeSpan.TicksPerSecond);
            }
            return DateTime.Parse(source);
        }
    }
}
